package com.zhida.jiyangcenter.mian.fragment

import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import chooongg.base.annotation.ContentLayout
import chooongg.base.loadState.LoadService
import chooongg.base.loadState.LoadUtils
import chooongg.base.loadState.callback.EmptyCallback
import chooongg.base.loadState.callback.ErrorCallback
import chooongg.base.loadState.callback.NetworkCallback
import chooongg.base.utils.*
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.base.widget.recyclerView.divider.VerticalDividerItemDecoration
import chooongg.http.APIException
import cn.sharesdk.wechat.utils.m
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.zhida.jiyangcenter.DEFAULT_ROW
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.APIShop
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.api.StoreListEntity
import com.zhida.jiyangcenter.buycar.BuyCarActivity
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.mian.BaseFragment
import com.zhida.jiyangcenter.modle.HealthyTestStroeActivity
import com.zhida.jiyangcenter.utils.NavigationUtils
import com.zhida.jiyangcenter.utils.getLocation
import com.zhida.jiyangcenter.utils.glideImage
import com.zhida.jiyangcenter.utils.request
import com.zhida.jiyangcenter.widget.NiceImageView
import kotlinx.android.synthetic.main.fragment_main_store.*

@ContentLayout(R.layout.fragment_main_store)
class MainStoreFragment : BaseFragment() {
    override fun getTitle(): CharSequence {
        return "门店"
    }

    private val data =
        arrayOf("北京", "石家庄")

    //声明AMapLocationClient类对象
    private lateinit var locationClient: AMapLocationClient
    var page = 1
    var adapter = Adapter()
    var city = ""
    var latitude = 0.0
    var longitude = 0.0
    lateinit var adapters: ArrayAdapter<String>
    private lateinit var loadService: LoadService<*>

    override fun initConfig(savedInstanceState: Bundle?) {
        super.initConfig(savedInstanceState)
        loadService = LoadUtils.getDefault().register(rv_store) {
            page = 1
            getData()
        }
        view_status_bar.updateLayoutParams<ConstraintLayout.LayoutParams> {
            height = getStatusBarHeight()
        }
        rv_store.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rv_store.adapter = adapter
        iv_store_search.setOnClickListener {
            ll_store_search.visible()
            iv_store_search.gone()
        }
        edit_text.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                page = 1
                search = edit_text.text.toString()
                iv_store_search.visible()
                ll_store_search.gone()
                val manager: InputMethodManager =
                    requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                manager.hideSoftInputFromWindow(
                    requireView().windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS
                )
                getData()
            }
            false
        }
        adapter.setOnLoadMoreListener({
            ++page
            getData()
        }, rv_store)
        rv_store.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(requireContext())
                .sizeResId(R.dimen.marginContentSmall).colorResId(R.color.colorBack).build()
        )
        iv_store_buycar.setOnClickListener {
            startActivity<BuyCarActivity> {

            }
        }
        tv_store_address.setOnClickListener {
            locationClient.startLocation()
        }
        locationClient = getLocation(requireContext()) {
            if (it.errorCode == AMapLocation.LOCATION_SUCCESS) {// 定位成功
                tv_store_address.text = it.city
                city = it.city
                latitude = it.latitude
                longitude = it.longitude
                getData()
            } else {// 定位失败
                logE("${it.errorCode}定位失败：${it.errorInfo ?: "未知原因"}")
            }
        }
        bga_store_top.setDelegate { banner, itemView, model, position ->
            if (model is StoreListEntity.Examination)
                startActivity<HealthyTestStroeActivity> {
                    putExtra("uuid", model.uuid)
                    putExtra("type", "0")
                }
        }
        adapter.setOnItemClickListener { _, view, position ->
            startActivity<HealthyTestStroeActivity> {
                putExtra("uuid", adapter.data[position].uuid)
                putExtra("type", "1")
            }
        }
        adapter.setOnItemChildClickListener { _, view, position ->
            NavigationUtils.startNavigationToOutApp(activity as BaseActivity , adapter.data[position].longitude?:0.00, adapter.data[position].latetude?:0.00, adapter.data[position].name)
        }
        bga_store_top.setAdapter { banner, itemView, model, position ->
            if (model != null && model is StoreListEntity.Examination) {
                glideImage(
                    itemView.findViewById<NiceImageView>(R.id.bg_store_banner),
                    model.picture ?: ""
                )
                itemView.findViewById<TextView>(R.id.tv_store_address).text = model.address
                itemView.findViewById<TextView>(R.id.tv_store_name).text = model.name
                itemView.findViewById<TextView>(R.id.tv_store_distance).text =
                    "距我${model.distance}km"
                itemView.findViewById<TextView>(R.id.tv_store_time).text =
                    "营业时间：${model.start_time}-${model.end_time}"
            }
        }
        ll_store_search_left.setOnClickListener {
            tv_store_search_left.setTextColor(resColor(R.color.colorPrimary))
            tv_store_search_right.setTextColor(resColor(R.color.textColor))
            type = "1"
            page = 1
            getData()
        }
        ll_store_search_right.setOnClickListener {
            tv_store_search_right.setTextColor(resColor(R.color.colorPrimary))
            tv_store_search_left.setTextColor(resColor(R.color.textColor))
            type = "0"
            page = 1
            getData()
        }


        //将可选内容与ArrayAdapter连接起来
        adapters = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, data)

        //设置下拉列表的风格
        adapters.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)


        //将adapter 添加到spinner中
        Spinner01.adapter = adapters

        //添加事件Spinner事件监听
        Spinner01.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {

            }

            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                city = data[position]
                tv_store_address.text=city
                page==1
                getData()
            }

        }

        //设置默认值
        Spinner01.setVisibility(View.VISIBLE)
    }

    override fun onResume() {
        super.onResume()
        getData()
    }

    override fun onPause() {
        locationClient.stopLocation()
        super.onPause()
    }

    override fun onDestroy() {
        locationClient.onDestroy()
        super.onDestroy()
    }

    var type = "1"
    var search = ""
    private fun getData() {
        lifecycleScope.request({
            APIShop.service().storeList(city, longitude, latitude, page, type, search)
        }, object : BaseAPI<StoreListEntity>() {
            override fun onSuccess(t: StoreListEntity?, state: Int, msg: String) {
                bga_store_top.setData(R.layout.item_main_store_banner, t?.examination, null)
                if (t != null && !t.health.isNullOrEmpty()) {
                    if (page <= 1) {
                        adapter.setNewData(t.health)
                        loadService.showSuccess()
                        if (t.health.size < DEFAULT_ROW) {
                            adapter.loadMoreEnd(true)
                        }
                    } else {
                        adapter.addData(t.health)
                        if (t.health.size < DEFAULT_ROW) {
                            adapter.loadMoreEnd(true)
                        } else adapter.loadMoreComplete()
                    }
                } else onError(APIException(APIException.Type.EMPTY))
            }

            override fun onError(e: APIException) {
                if (page <= 1) when (e.type) {
                    APIException.Type.EMPTY -> loadService.showCallback(
                        EmptyCallback::class,
                        "暂无服务"
                    )
                    APIException.Type.ERROR_NETWORK -> loadService.showCallback(NetworkCallback::class)
//                        APIException.Type.NOT_LOGIN -> loadService.showCallback(NotLoginCallback::class)
                    else -> loadService.showCallback(ErrorCallback::class, e.eMessage)
                } else when (e.type) {
                    APIException.Type.EMPTY -> {
                        adapter.loadMoreFail()
                    }
                    else -> adapter.loadMoreFail()
                }
            }

        })
    }

    class Adapter :
        BaseQuickAdapter<StoreListEntity.Health, BaseViewHolder>(R.layout.item_fragmnet_main_store) {
        override fun convert(helper: BaseViewHolder, item: StoreListEntity.Health?) {
            glideImage(helper.getView(R.id.civ_fragment_main_store), item?.picture ?: "")
            helper.setText(R.id.tv_store_title, item?.name)
                .setText(R.id.tv_store_address, item?.distance + "km")
                .addOnClickListener(R.id.tv_store_address)

            val rv_store_tab = helper.getView<RecyclerView>(R.id.rv_store_tab)
            rv_store_tab.layoutManager =
                object : LinearLayoutManager(mContext, HORIZONTAL, false) {
                    override fun canScrollHorizontally(): Boolean {
                        return false
                    }
                }
            rv_store_tab.adapter = TabAdapter().apply {
                setNewData(item?.label?.split("，"))
            }
            if (rv_store_tab.itemDecorationCount == 0)
                rv_store_tab.addItemDecoration(
                    VerticalDividerItemDecoration.Builder(mContext)
                        .sizeResId(R.dimen.d4).colorResId(R.color.white).build()
                )
            val rv_store_project = helper.getView<RecyclerView>(R.id.rv_store_project)
            rv_store_project.layoutManager = object : LinearLayoutManager(mContext) {
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            rv_store_project.adapter = ProjectAdapter().apply {
                setNewData(item?.serve)
            }
            if (rv_store_project.itemDecorationCount == 0)
                rv_store_project.addItemDecoration(
                    HorizontalDividerItemDecoration.Builder(mContext)
                        .sizeResId(R.dimen.d4).colorResId(R.color.white).build()
                )

        }

        class TabAdapter :
            BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_fragment_main_store_tab) {
            override fun convert(helper: BaseViewHolder, item: String?) {
                helper.setText(R.id.tv_tab, item)
            }

        }

        class ProjectAdapter :
            BaseQuickAdapter<StoreListEntity.Health.Serve, BaseViewHolder>(R.layout.item_fragment_store_project) {
            override fun convert(helper: BaseViewHolder, item: StoreListEntity.Health.Serve?) {
                helper.setText(
                    R.id.tv_project,
                    "${item?.name}"//￥${item?.max_money}   会员价${item?.min_money}元
                )
            }

        }
    }
}